<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <h1 class="title">
        <i class="el-icon-data-analysis"></i>
        数据大屏
      </h1>
      <div class="current-time">{{ currentTime }}</div>
    </div>

    <!-- 核心数据卡片 -->
    <div class="stats-cards">
      <div class="stat-card" v-for="(item, index) in statsCards" :key="index">
        <div class="card-icon" :style="{ backgroundColor: item.color }">
          <i :class="item.icon"></i>
        </div>
        <div class="card-content">
          <div class="card-title">{{ item.title }}</div>
          <div class="card-value">
            <AnimatedNumber :value="item.value" :duration="2000" />
          </div>
          <div class="card-trend" :class="item.trend.type">
            <i :class="item.trend.icon"></i>
            {{ item.trend.text }}
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 第一行图表 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">用户增长趋势</div>
          <div id="userGrowthChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">题目类型分布</div>
          <div id="questionTypeChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">活跃度统计</div>
          <div id="activityChart" class="chart"></div>
        </div>
      </div>

      <!-- 第二行图表 -->
      <div class="chart-row">
        <div class="chart-item large">
          <div class="chart-title">分类题目统计</div>
          <div id="categoryChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">难度分布</div>
          <div id="difficultyChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import dashboardApi from '@/api/dashboard'
import AnimatedNumber from '@/components/AnimatedNumber.vue'

export default {
  name: 'Dashboard',
  components: {
    AnimatedNumber
  },
  data() {
    return {
      currentTime: '',
      statsCards: [
        {
          title: '用户总数',
          value: 0,
          icon: 'el-icon-user',
          color: '#409EFF',
          trend: { type: 'up', text: '+12%', icon: 'el-icon-arrow-up' }
        },
        {
          title: '题目总数',
          value: 0,
          icon: 'el-icon-document',
          color: '#67C23A',
          trend: { type: 'up', text: '+8%', icon: 'el-icon-arrow-up' }
        },
        {
          title: '试卷总数',
          value: 0,
          icon: 'el-icon-files',
          color: '#E6A23C',
          trend: { type: 'up', text: '+5%', icon: 'el-icon-arrow-up' }
        },
        // {
        //   title: '分类总数',
        //   value: 0,
        //   icon: 'el-icon-menu',
        //   color: '#F56C6C',
        //   trend: { type: 'up', text: '+3%', icon: 'el-icon-arrow-up' }
        // }
      ],
      statisticsData: null
    }
  },
  mounted() {
    this.updateTime()
    this.loadStatistics()
    // 每秒更新时间
    setInterval(this.updateTime, 1000)
  },
  methods: {
    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },

    async loadStatistics() {
      try {
        const response = await dashboardApi.getStatistics()
        this.statisticsData = response.data
        this.updateStatsCards()
        this.$nextTick(() => {
          this.initCharts()
        })
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },

    updateStatsCards() {
      if (this.statisticsData && this.statisticsData.basicStats) {
        const stats = this.statisticsData.basicStats
        this.statsCards[0].value = stats.totalUsers
        this.statsCards[1].value = stats.totalQuestions
        this.statsCards[2].value = stats.totalPapers
        // 只有当第4个卡片存在时才更新
        if (this.statsCards[3]) {
          this.statsCards[3].value = stats.totalCategories
        }
      }
    },

    initCharts() {
      this.initUserGrowthChart()
      this.initQuestionTypeChart()
      this.initActivityChart()
      this.initCategoryChart()
      this.initDifficultyChart()
    },

    initUserGrowthChart() {
      const chart = echarts.init(document.getElementById('userGrowthChart'))
      const data = this.statisticsData.userGrowth || []

      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#409EFF',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.date),
          axisLine: {
            lineStyle: {
              color: '#409EFF'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#409EFF'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(64, 158, 255, 0.1)'
            }
          }
        },
        series: [{
          data: data.map(item => item.count),
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#409EFF',
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(64, 158, 255, 0.6)'
              }, {
                offset: 1, color: 'rgba(64, 158, 255, 0.1)'
              }]
            }
          },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }

      chart.setOption(option)
    },

    initQuestionTypeChart() {
      const chart = echarts.init(document.getElementById('questionTypeChart'))
      const data = this.statisticsData.questionTypes || []

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          textStyle: {
            color: '#666'
          }
        },
        series: [{
          name: '题目类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '30',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          }
        }]
      }

      chart.setOption(option)
    },

    initActivityChart() {
      const chart = echarts.init(document.getElementById('activityChart'))
      const data = this.statisticsData.recentActivity || []

      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#67C23A',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.time),
          axisLine: {
            lineStyle: {
              color: '#67C23A'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#67C23A'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(103, 194, 58, 0.1)'
            }
          }
        },
        series: [{
          data: data.map(item => item.activity),
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#67C23A'
              }, {
                offset: 1, color: '#85CE61'
              }]
            },
            borderRadius: [4, 4, 0, 0]
          }
        }]
      }

      chart.setOption(option)
    },

    initCategoryChart() {
      const chart = echarts.init(document.getElementById('categoryChart'))
      const data = this.statisticsData.categoryStats || []

      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#E6A23C',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLine: {
            lineStyle: {
              color: '#E6A23C'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#E6A23C'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(230, 162, 60, 0.1)'
            }
          }
        },
        series: [{
          data: data.map(item => item.value),
          type: 'bar',
          barWidth: '50%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#E6A23C'
              }, {
                offset: 1, color: '#EEBE77'
              }]
            },
            borderRadius: [4, 4, 0, 0]
          }
        }]
      }

      chart.setOption(option)
    },

    initDifficultyChart() {
      const chart = echarts.init(document.getElementById('difficultyChart'))
      const data = this.statisticsData.difficultyLevels || []

      const colors = ['#67C23A', '#E6A23C', '#F56C6C']

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '难度分布',
          type: 'pie',
          radius: '70%',
          data: data.map((item, index) => ({
            ...item,
            itemStyle: {
              color: colors[index % colors.length]
            }
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            color: '#666'
          }
        }]
      }

      chart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  color: #333;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);

  .title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    margin: 0;

    i {
      color: #409EFF;
      margin-right: 10px;
    }
  }

  .current-time {
    font-size: 18px;
    color: #666;
    font-weight: 500;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 25px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
  }

  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;

    i {
      font-size: 24px;
      color: white;
    }
  }

  .card-content {
    flex: 1;

    .card-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 5px;
    }

    .card-value {
      font-size: 28px;
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
    }

    .card-trend {
      font-size: 12px;

      &.up {
        color: #67C23A;
      }

      &.down {
        color: #F56C6C;
      }

      i {
        margin-right: 2px;
      }
    }
  }
}

.charts-container {
  .chart-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .chart-item {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 15px;
    padding: 20px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);

    &.large {
      grid-column: span 2;
    }

    .chart-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 15px;
      text-align: center;
    }

    .chart {
      height: 300px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .dashboard-header {
    flex-direction: column;
    text-align: center;

    .title {
      margin-bottom: 10px;
    }
  }

  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }

  .chart-row {
    grid-template-columns: 1fr !important;
  }

  .chart-item {
    &.large {
      grid-column: span 1;
    }
  }
}
</style>
